//
//  TJForgetPasswordController.m
//  CrossBorderPayment
//
//  Created by hc-101 on 2020/6/9.
//  Copyright © 2020 xtjun. All rights reserved.
//

#import "TJForgetPasswordController.h"
#import "UIButton+LXMImagePosition.h"
#import "TJSettingPasswController.h"
#import "TJSelectCityController.h"

@interface TJForgetPasswordController ()
/**是否邮箱验证 */
@property (assign, nonatomic) BOOL isEmailValidation;

@property (weak, nonatomic) UITextField *emailTextField;
@property (weak, nonatomic) UITextField *phoneTextField;
@property (weak, nonatomic) UIButton *areaButton;
@property (weak, nonatomic) UILabel *mailValidationLabel;
@property (weak, nonatomic) UIView *bottomView;
@property (weak, nonatomic) UIView *SMSView;
@property (weak, nonatomic) UILabel *sendTipLabel;
@property (weak, nonatomic) UILabel *resendLabel;
@property (weak, nonatomic) UITextField *SMSTextField;
@property (assign, nonatomic) BOOL isShowSMSView;

@property (copy, nonatomic) NSString *areaCode;

@end

@implementation TJForgetPasswordController {
    dispatch_source_t _sendSMSTimer;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationBar.lineView.hidden = YES;
    
    self.view.backgroundColor = UIColor.whiteColor;
    _areaCode = @"+86";
    UILabel *titleLabel = [UILabel lableWithSuperView:self.view font:UIFont_Px(24) color:UIColor_Hex(0x262626) title:@"忘记密码".localizedString textAlignment:NSTextAlignmentLeft];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(36);
        make.top.offset(KNavBarHight + 46);
    }];
    
    UILabel *registeredTipLabel = [UILabel lableWithSuperView:self.view font:UIFont_Px(14) color:UIColor_Hex(0xC2C2C2) title:@"通过您的手机或者邮箱找回密码".localizedString textAlignment:NSTextAlignmentLeft];
    [registeredTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(36);
        make.top.equalTo(titleLabel.mas_bottom).offset(16);
    }];
    
    
    UIButton *areaButton = [UIButton buttonWithSuperView:self.view font:UIFont_Px(14) color:UIColor_Hex(0x262626) title:_areaCode];
    [areaButton setImage:[UIImage imageNamed:@"areaArrowIcon"] forState:UIControlStateNormal];
    [areaButton setImage:[UIImage imageNamed:@"areaArrowIcon"] forState:UIControlStateHighlighted];
    [areaButton setContentHorizontalAlignment:(UIControlContentHorizontalAlignmentLeft)];
    [areaButton addTarget:self action:@selector(didClickAreaButton) forControlEvents:UIControlEventTouchUpInside];
    [areaButton setImagePosition:LXMImagePositionRight spacing:4];
    [areaButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLabel);
        make.top.equalTo(registeredTipLabel.mas_bottom).offset(44);
        make.width.offset(50);
        make.height.offset(24);
    }];
    
    UITextField *phoneTextField = [UITextField tj_addToView:self.view];
    phoneTextField.placeholder = @"请输入手机号码".localizedString;
    phoneTextField.font = UIFont_Px(15);
    phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    [phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(areaButton.mas_right).offset(16);
        make.centerY.equalTo(areaButton);
        make.height.offset(34);
        make.right.offset(-36);
    }];
    
    UITextField *emailTextField = [UITextField tj_addToView:self.view];
    emailTextField.placeholder = @"请输入您的邮箱账户".localizedString;
    emailTextField.font = UIFont_Px(15);
    emailTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    emailTextField.keyboardType = UIKeyboardTypeEmailAddress;
    [emailTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLabel);
        make.centerY.equalTo(areaButton);
        make.height.offset(34);
        make.right.offset(-36);
    }];
    
    UIView *lineView = [UIView tj_addToView:self.view];
    lineView.backgroundColor = UIColor_Hex(0xE5E5E5);
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(areaButton);
        make.right.equalTo(phoneTextField);
        make.height.offset(1);
        make.top.equalTo(phoneTextField.mas_bottom).offset(2);
    }];
    
    
    UIView *bottomView = [self addBottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.equalTo(lineView.mas_bottom).offset(50);
    }];
    
    UIView *SMSView = [self addSMSView];
    [SMSView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.equalTo(lineView.mas_bottom).offset(50);
    }];
    
    _areaButton = areaButton;
    _phoneTextField = phoneTextField;
    _emailTextField = emailTextField;
    
    
    self.isEmailValidation = NO;
    self.isShowSMSView = NO;
}

- (UIView *)addSMSView {
    
    UIView *SMSView = [UIView tj_addToView:self.view];
    SMSView.backgroundColor = UIColor_Hex(0xF2F2F2);
    _SMSView = SMSView;
    
    UILabel *validationErrorLabel = [UILabel lableWithSuperView:SMSView font:UIFont_Px(12) color:UIColor_Hex(0x8F8F8F) title:@"如无法验证请联系客服".localizedString textAlignment:NSTextAlignmentLeft];
    [validationErrorLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(36);
        make.top.offset(15);
    }];
    
    UILabel *validationLabel = [UILabel lableWithSuperView:SMSView font:UIFont_Px(14) color:UIColor_Hex(0x262626) title:@"安全验证".localizedString textAlignment:NSTextAlignmentLeft];
    [validationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(36);
        make.top.equalTo(validationErrorLabel.mas_bottom).offset(20);
    }];
    
    UILabel *cancelLabel = [UILabel lableWithSuperView:SMSView font:UIFont_Px(12) color:UIColor_Hex(0x8F8F8F) title:@"取消".localizedString textAlignment:NSTextAlignmentLeft];
    [cancelLabel addTapGesturesWithTarget:self action:@selector(tapCancelLabel)];
    [cancelLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-36);
        make.centerY.equalTo(validationLabel);
    }];
    
    UILabel *sendTipLabel = [UILabel lableWithSuperView:SMSView font:UIFont_Px(12) color:UIColor_Hex(0x8F8F8F) title:@"" textAlignment:NSTextAlignmentLeft];
    [sendTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(36);
        make.top.equalTo(validationLabel.mas_bottom).offset(23);
    }];
    
    
    QMUITextField *SMSTextField = [QMUITextField tj_addToView:SMSView];
    SMSTextField.placeholder = @"请输入验证码".localizedString;
    SMSTextField.maximumTextLength = 6;
    SMSTextField.keyboardType = UIKeyboardTypeNumberPad;
    SMSTextField.font = UIFont_Px(15);
    [SMSTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(150);
        make.left.offset(36);
        make.height.offset(30);
        make.top.equalTo(sendTipLabel.mas_bottom).offset(8);
    }];
    
    UIView *lineView = [UIView tj_addToView:SMSView];
       lineView.backgroundColor = UIColor_Hex(0xE5E5E5);
       [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
           make.left.right.equalTo(SMSTextField);
           make.height.offset(1);
           make.top.equalTo(SMSTextField.mas_bottom).offset(5);
       }];
    
    UILabel *resendLabel = [UILabel lableWithSuperView:SMSView font:UIFont_Px(12) color:UIColor_Hex(0x262626) title:@"重新发送".localizedString textAlignment:NSTextAlignmentLeft];
    [resendLabel addTapGesturesWithTarget:self action:@selector(tapResendLabel)];
    [resendLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-36);
        make.centerY.equalTo(SMSTextField);
    }];
    
    
    UIButton *determineButton = [UIButton buttonWithSuperView:SMSView font:UIFont_Px(18) color:UIColor.whiteColor title:@"下一步".localizedString];
    determineButton.backgroundColor = UIColor_Hex(0x2C6CC7);
    [determineButton shearRoundedCornersWithRadiu:22];
    [determineButton addTarget:self action:@selector(didClickDetermineButton) forControlEvents:UIControlEventTouchUpInside];
    [determineButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-36);
        make.left.offset(36);
        make.height.offset(44);
        make.centerX.offset(0);
        make.bottom.offset(-TabbarSafeBottomMargin - 64);
    }];
    
    _sendTipLabel = sendTipLabel;
    _resendLabel = resendLabel;
    _SMSTextField = SMSTextField;
    
    return SMSView;
}

- (UIView *)addBottomView {
    
    UIView *bottomView = [UIView tj_addToView:self.view];
    bottomView.backgroundColor = UIColor.whiteColor;
    _bottomView = bottomView;
    
    
    UIButton *nextButton = [UIButton buttonWithSuperView:bottomView font:UIFont_Px(18) color:UIColor.whiteColor title:@"下一步".localizedString];
    nextButton.backgroundColor = UIColor_Hex(0x2C6CC7);
    [nextButton shearRoundedCornersWithRadiu:22];
    [nextButton addTarget:self action:@selector(didClickNextButton) forControlEvents:UIControlEventTouchUpInside];
    [nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(36);
        make.right.offset(-36);
        make.height.offset(44);
        make.top.offset(20);
    }];
    
    UILabel *mailValidationLabel = [UILabel lableWithSuperView:bottomView font:UIFont_Px(14) color:UIColor_Hex(0x262626) title:@"邮箱验证".localizedString textAlignment:NSTextAlignmentLeft];
    [mailValidationLabel addTapGesturesWithTarget:self action:@selector(tapValidationWayLabel)];
    [mailValidationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(nextButton);
        make.top.equalTo(nextButton.mas_bottom).offset(14);
    }];
    
    
    return bottomView;
    
}


- (void)setIsShowSMSView:(BOOL)isShowSMSView {
    _isShowSMSView = isShowSMSView;
    
    _SMSView.hidden = !isShowSMSView;
    _bottomView.hidden = isShowSMSView;
}


- (void)tapCancelLabel {
    self.isShowSMSView = NO;
}


- (void)tapResendLabel {
    [self didClickNextButton];
}

/**下一步点击 */
- (void)didClickNextButton {
    
    [self.view endEditing:YES];
    
    NSMutableDictionary *parameters = @{}.mutableCopy;
    //    [parameters setObject:@"4" forKey:@"scene"];
    NSString *url = @"";
    if (_isEmailValidation) {
        url = @"data/sms/sendMail";
        NSString *email = _emailTextField.text;
        
        if (!email.length) {
            [TJHud showAutoHideMessage:_emailTextField.placeholder];
            return;
        }
        [parameters setObject:email forKey:@"mailbox"];
        
        
    } else {
        url = @"data/sms/sendSms";
        NSString *phone = _phoneTextField.text;
        if (!phone.length) {
            [TJHud showAutoHideMessage:_phoneTextField.placeholder];
            return;
        }
        
        [parameters setObject:phone forKey:@"phone"];
        
        [parameters setObject:_areaCode forKey:@"phoneCode"];
        
    }
    NSString *type = @"";
    if (self.isPay) {
        type = @"PAYRESET";
    }else{
        type = @"RETRIEVE";
    }
    [parameters setObject:type forKey:@"type"];//忘记密码
    
    [TJNetworking.shareNetworking POSTNew:url parameters:parameters success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        
        self.isShowSMSView = YES;
        
        if (self.isEmailValidation) {//邮箱
            self.sendTipLabel.text = [NSString stringWithFormat:@"验证码已发送至%@".localizedString, self.emailTextField.text];
        } else {
            self.sendTipLabel.text = [NSString stringWithFormat:@"验证码已发送至%@".localizedString, self.phoneTextField.text];
        }
        
        self.SMSTextField.text = nil;
        
        [TJHud showAutoHideMessage:@"发送成功".localizedString];
        //开始倒计时
        [self startCountdown];
        
    } failure:^(NSError * _Nonnull error) {
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
}

- (void)startCountdown {
    
    [self setSMSCodeEnable:NO];
    
    __block NSInteger timestamp = 120;
    
    dispatch_source_t sendSMSTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
    dispatch_source_set_timer(sendSMSTimer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(sendSMSTimer, ^{
        
        timestamp--;
        
        if (timestamp <= 0) {
            dispatch_source_cancel(sendSMSTimer);
            dispatch_async(dispatch_get_main_queue(), ^{//显示GO
                self.resendLabel.text = @"重新发送".localizedString;
                [self setSMSCodeEnable:YES];
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.resendLabel.text = [NSString stringWithFormat:@"%lds", timestamp];
                [self setSMSCodeEnable:NO];
            });
        }
    });
    _sendSMSTimer = sendSMSTimer;
    dispatch_resume(sendSMSTimer);
}


- (void)setSMSCodeEnable:(BOOL)SMSCodeEnable {
    
    if (SMSCodeEnable) {
        _resendLabel.userInteractionEnabled = YES;
    } else {
        _resendLabel.userInteractionEnabled = NO;
    }
}


/**获取验证码之后的下一步 */
- (void)didClickDetermineButton {
    
    
    [self.view endEditing:YES];
    
    
    NSString *SMSCode = _SMSTextField.text;
    
    if (!SMSCode.length) {
        [TJHud showAutoHideMessage:_SMSTextField.placeholder];
        return;
    }
    
    NSMutableDictionary *parameters = @{}.mutableCopy;
    
    if (_isEmailValidation) {
        
        NSString *email = _emailTextField.text;
        
        if (!email.length) {
            [TJHud showAutoHideMessage:_emailTextField.placeholder];
            return;
        }
        
        [parameters setObject:email forKey:@"phMail"];
        
    } else {
        
        NSString *phone = _phoneTextField.text;
        if (!phone.length) {
            [TJHud showAutoHideMessage:_phoneTextField.placeholder];
            return;
        }
        
        [parameters setObject:phone forKey:@"phMail"];
    }
    
    [parameters setObject:SMSCode forKey:@"code"];
    
    TJSettingPasswController *settingPasswController = [[TJSettingPasswController alloc] init];
    settingPasswController.parameters = parameters;
    settingPasswController.type = 2;
    settingPasswController.isEmailValidation = _isEmailValidation;
    settingPasswController.isPay = self.isPay;
    [self.navigationController pushViewController:settingPasswController animated:YES];
}

/**邮箱验证 */
- (void)tapValidationWayLabel {
    self.isEmailValidation = !self.isEmailValidation;
}

- (void)setIsEmailValidation:(BOOL)isEmailValidation {
    _isEmailValidation = isEmailValidation;
    
    _emailTextField.hidden = !isEmailValidation;
    _phoneTextField.hidden = isEmailValidation;
    _areaButton.hidden = isEmailValidation;
    _mailValidationLabel.text = isEmailValidation ? @"手机验证".localizedString : @"邮箱验证".localizedString;
    
}
/**区域切换点击 */
- (void)didClickAreaButton {
    TJSelectCityController *selectCityController = [[TJSelectCityController alloc] init];
    [selectCityController setSelectComplete:^(TJSelectCityModel * _Nonnull model) {
        [self.areaButton setTitle:model.code forState:UIControlStateNormal];
        [self.areaButton setImagePosition:LXMImagePositionRight spacing:4];
        self.areaCode = model.code;
    }];
    [self presentViewController:selectCityController animated:YES completion:nil];
}

@end
